package com.mini.controller;

import com.mini.conditon.BaseCondition;
import com.mini.service.AliOSSService;
import com.mini.service.MiniAdminService;
import com.mini.service.TencentUploadService;
import com.mini.util.AsyncTaskManager;
import com.mini.util.CalendarUtil;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisCommands;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author zhangxiaobin
 * @title: BaseController
 * @description: TODO
 * @date 2019/10/2711:35
 */
@Slf4j
public class BaseController {

    @Value("${mini.eureka.call.sign}")
    String sign;

    protected static final String conact_time = " 16:00:00";

    @Autowired
    AsyncTaskManager asyncTaskManager;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    AliOSSService ossService;

    @Autowired
    HttpServletRequest request;
    @Autowired
    private MiniAdminService miniAdminService;

    @Autowired
    TencentUploadService tencentUploadService;

    protected boolean tryLock(String key, long time) {
        try {
            String result = (String) redisTemplate.execute((RedisCallback<String>) connection -> {
                JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                return commands.set(key, key, "NX", "EX", time);
            });
            return !StringUtils.isEmpty(result);
        } catch (Exception e) {
            log.error("getNewUsePushLock error", e);
        }
        return false;
    }

    protected boolean tryLock(String key) {
        try {
            String result = (String) redisTemplate.execute((RedisCallback<String>) connection -> {
                JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                return commands.set(key, key, "NX", "EX", 5);
            });
            return !StringUtils.isEmpty(result);
        } catch (Exception e) {
            log.error("getNewUsePushLock error", e);
        }
        return false;
    }

    protected void releaseLockKey(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("releaseNewUsePushLock error", e);
        }
    }

    protected void checkPageParams(BaseCondition baseCondition) {
        if (baseCondition.getPageNumber().intValue() < 1) {
            baseCondition.setPageNumber(1);
        }

        if (baseCondition.getPageSize().intValue() < 10 || baseCondition.getPageSize().intValue() > 200) {
            baseCondition.setPageSize(10);
        }
    }

    protected void checkPageParams8(BaseCondition baseCondition) {
        if (baseCondition.getPageNumber().intValue() < 1) {
            baseCondition.setPageNumber(1);
        }

        if (baseCondition.getPageSize().intValue() < 8 || baseCondition.getPageSize().intValue() > 200) {
            baseCondition.setPageSize(8);
        }
    }

    protected void checkNoPageParams(BaseCondition baseCondition) {
        if (baseCondition.getPageNumber().intValue() < 1) {
            baseCondition.setPageNumber(1);
        }
    }

    protected boolean checkDate(String beginTime, String endTime) {
        try {
            CalendarUtil.parseDate(beginTime, CalendarUtil.SHORT_DATE_FORMAT);
            CalendarUtil.parseDate(endTime, CalendarUtil.SHORT_DATE_FORMAT);
        } catch (Exception ex) {
            log.error("日期格式错误 {} , {}", beginTime, endTime);
            return true;
        }
        return false;
    }

    protected boolean checkDateTime(String dateTimeStr) {
        try {
            CalendarUtil.parseDate(dateTimeStr, CalendarUtil.SIMPLE_DATE_FORMAT);
        } catch (Exception ex) {
            log.error("日期格式错误 {} ", dateTimeStr);
            return true;
        }
        return false;
    }

    protected boolean checkSign(String requestSig) {
        if (StringUtils.isBlank(requestSig)) {
            return false;
        }
        if (sign.equalsIgnoreCase(requestSig)) {
            return true;
        }
        return false;
    }

    public UserVO getLoginUser(String token) {
        UserVO userVO = getLoginUserFromRequest();
        if (Objects.nonNull(userVO)) {
            return userVO;
        }
        return miniAdminService.getLoginUser(token);
    }

    /**
     * 走登录拦截器的可以直接获取
     *
     * @return
     */
    public UserVO getLoginUserFromRequest() {
        UserVO userVO = (UserVO) request.getAttribute("_LOGIN_USER_INFO");
        return userVO;
    }

    protected static Workbook getWorkbook(InputStream inputStream, String fileName) throws Exception {
        Workbook workbook;
        if (fileName.endsWith(Suffix.XLS.value)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileName.endsWith(Suffix.XLSX.value)) {
            workbook = new XSSFWorkbook(inputStream);
        } else {
            throw new IllegalArgumentException("请上传excel文件！");
        }
        return workbook;
    }

    enum Suffix {
        XLS(".xls"),
        XLSX(".xlsx"),
        ;

        final String value;

        Suffix(String value) {
            this.value = value;
        }
    }
}